﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WebTest.Core.Interfaces;
using WebTest.WebApi.Models;

namespace WebTest.WebApi.Controllers
{
    [Route("[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class TokenController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IMemberSignService memberSign;

        public TokenController(IConfiguration configuration, IMemberSignService memberSign)
        {
            this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.memberSign = memberSign ?? throw new ArgumentNullException(nameof(memberSign));
        }

        //[HttpPost("RequestToken")]
        //public async Task<string> RequestTokenAsync(MemberSignInModel model)
        //{
        //    //var member = await memberSign.SignIn(model.UserName, model.Password);

        //    //// 登陆失败
        //    //if(member == null)
        //    //{
        //    //    //return BadRequest();
        //    //    return JsonSerializer.Serialize(new TokenModel { Message = "账号或密码不正确." });
        //    //}

        //    //var issuer = configuration["JwtToken:Issuer"];
        //    //var audience = configuration["JwtToken:Audience"];
        //    //var serect = configuration["JwtToken:Serect"];
        //    //var claims = new[]
        //    //{
        //    //    new Claim(ClaimTypes.Sid, member.Id.ToString()),
        //    //    new Claim(ClaimTypes.Name, member.MemberName),
        //    //    new Claim(ClaimTypes.Role, "Admin")
        //    //};

        //    //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serect));
        //    //var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        //    //var jwtSecurityToken = new JwtSecurityToken(
        //    //    issuer:issuer,
        //    //    audience: audience,
        //    //    claims: claims,
        //    //    expires: DateTime.UtcNow.AddMinutes(120),
        //    //    signingCredentials: creds);

        //    //var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        //    //var json = JsonSerializer.Serialize(new TokenModel { Token = token });

        //    //return json;
        //    return string.Empty;
        //}
        [HttpPost]
        public IActionResult GetToken()
        {
            var authorizationHeader = Request.Headers["Authorization"].First();
            var key = authorizationHeader.Split(' ')[1];
            var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(key)).Split(':');

            var serverSecret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtToken:Serect"]));
            //验证是否是信任用户的用户名和密码,可在数据库中查询
            if (credentials[0] == "awesome-username" && credentials[1] == "awesome-password")
            {
                var result = new
                {
                    token = GenerateToken(serverSecret)
                };

                return Ok(result);
            }

            return BadRequest();
        }
        [HttpPost("Test")]
        public string Test()
        {
            var identity = "awesome-username:awesome-password";
            string idString = Convert.ToBase64String(Encoding.UTF8.GetBytes(identity));
            return idString;
        }
        private string GenerateToken(SecurityKey key)
        {
            var now = DateTime.UtcNow;
            //发行人
            var issuer = configuration["JwtToken:Issuer"];
            //接收者??
            var audience = configuration["JwtToken:Audience"];
            var identity = new ClaimsIdentity();
            //可以放一些claim进去授权时候使用
            Claim claim = new Claim(ClaimTypes.Name, "Leo");
            identity.AddClaim(claim);
            //登录凭证
            var signingCredentials = new SigningCredentials(key,
                SecurityAlgorithms.HmacSha256);
            var handler = new JwtSecurityTokenHandler();
            //生成token,设置1小时的过期时间
            var token = handler.CreateJwtSecurityToken(issuer, audience, identity,
                now, now.Add(TimeSpan.FromDays(365)), now, signingCredentials);
            var encodedJwt = handler.WriteToken(token);
            return encodedJwt;
        }
    }
}
